package com.example.farmer.Adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.farmer.Database.CircleChooseDatabase;
import com.example.farmer.Database.CirclePostDatabase;
import com.example.farmer.Entity.CirclePost;
import com.example.farmer.R;

import java.util.ArrayList;
import java.util.List;

public class PostCircleAdapter extends RecyclerView.Adapter<PostCircleAdapter.PostViewHolder> {
    private static List<CirclePost> circlePosts;
    private static Context context;
    private CircleChooseDatabase circleChooseDatabase;
    private Uri selectedImageUri;
    private ArrayList<Uri> mImageUris = new ArrayList<>();


    // 构造函数，接收帖子列表和上下文

    public PostCircleAdapter(List<CirclePost> circlePosts, Context context ) {
        this.circlePosts = circlePosts;
        this.context = context;
        this.circleChooseDatabase = CircleChooseDatabase.getInstance(context);

    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 从布局文件中加载帖子项的视图
        View postView = LayoutInflater.from(parent.getContext()).inflate(R.layout.circle_post_item, parent, false);
        return new PostViewHolder(postView);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        // 获取当前位置的帖子对象
        CirclePost circlePost = circlePosts.get(position);
        // 绑定帖子内容和图片到ViewHolder
        holder.bind(circlePost);
        // 根据点赞状态设置图标
        if (circlePost.isLiked()) {
            holder.buttonLike.setImageResource(R.drawable.baseline_thumb_up_alt_24);
        } else {
            holder.buttonLike.setImageResource(R.drawable.baseline_thumb_up_off_alt_24);
        }

    }

    @Override
    public int getItemCount() {
        // 返回帖子列表的大小
        return circlePosts == null ? 0 : circlePosts.size();
    }

    // 更新帖子数据的方法
    @SuppressLint("NotifyDataSetChanged")
    public void updatePosts(List<CirclePost> newCirclePosts) {
        if (newCirclePosts != null) {
            this.circlePosts = newCirclePosts;
            notifyDataSetChanged(); // 通知数据集改变
        }
    }

    // ViewHolder内部类
    public class PostViewHolder extends RecyclerView.ViewHolder {
        TextView per_number;
        TextView dianpu;
        TextView guanzhu;
        TextView textViewContent;
        ImageView imagePostContent;
        TextView textDelete;
        ImageButton buttonLike;
        ImageButton buttonComment;



        public PostViewHolder(View itemView) {
            super(itemView);
            // 通过findViewById绑定视图组件
            per_number = itemView.findViewById(R.id.per_number);
            dianpu = itemView.findViewById(R.id.dianpu);
            guanzhu = itemView.findViewById(R.id.guanzhu);
            textViewContent = itemView.findViewById(R.id.text_view_post_content);
            imagePostContent = itemView.findViewById(R.id.image_view_post_image);
            textDelete = itemView.findViewById(R.id.text_delete);
            buttonLike = itemView.findViewById(R.id.button_like);
            buttonComment = itemView.findViewById(R.id.button_comment);

            // 初始化数据库帮助类实例
            circleChooseDatabase = CircleChooseDatabase.getInstance(context);

            //获取登录页面传来的number
            SharedPreferences sharedPreferences = context.getSharedPreferences("loginNumber", Context.MODE_PRIVATE);
            String userNumber = sharedPreferences.getString("userNumber" , "") ;
            // 隐藏手机号中间四位
            String hiddenNumber = hideMiddleFourDigits(userNumber);
            // 将隐藏后的手机号设置到TextView上
            per_number.setText(hiddenNumber);

            dianpu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "进店铺成功", Toast.LENGTH_SHORT).show();
                }
            });

//            guanzhu.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    // 获取当前帖子的相关信息，例如帖子ID或作者ID
//
//                    Toast.makeText(context, "关注成功", Toast.LENGTH_SHORT).show();
//
//                }
//            });

            guanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // 获取数据
                    String userNumber = per_number.getText().toString();
                    String content = textViewContent.getText().toString();
                    // 注意：确保您有方法来获取ImageView的图片URL
                    String imageUrl = imagePostContent.toString(); // 假设您已经设置了ImageView的tag为图片URL

                    // 检查是否已经关注
                    boolean isChoose = circleChooseDatabase.isChooseNumber(userNumber);
                    if (!isChoose) {
                        // 如果没有关注，则添加关注
                        long result = circleChooseDatabase.insertPost(userNumber,content,imageUrl);
                        if (result != -1) {
                            // 如果插入成功
                            Toast.makeText(context, "关注成功！", Toast.LENGTH_SHORT).show();
                            // 这里可以更新UI，比如改变按钮状态或更新帖子列表
                        } else {
                            // 如果插入失败
                            Toast.makeText(context, "关注失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        // 如果已经关注
                        Toast.makeText(context, "已被关注", Toast.LENGTH_SHORT).show();
                    }
                }
            });


            // 设置删除按钮的点击监听器
            textDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 删除帖子的逻辑
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        CirclePost circlePostToDelete = circlePosts.get(position);
                        CirclePostDatabase circlePostDatabase = CirclePostDatabase.getInstance(context);
                        circlePostDatabase.deletePost(circlePostToDelete.getId());

                        CirclePost circleChooseToDelete = circlePosts.get(position);
                        CircleChooseDatabase circleChooseDatabase = CircleChooseDatabase.getInstance(context);
                        circleChooseDatabase.deletePost(circleChooseToDelete.getUserNumber());

                        // 从列表中移除帖子，并更新UI
                        circlePosts.remove(position);
                        notifyItemRemoved(position);
                    }
                }
            });

            // 设置点赞和评论按钮的点击监听器（示例代码，具体逻辑需要您自己实现）
            // 点赞按钮点击事件
            buttonLike.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    CirclePost circlePost = circlePosts.get(position);
                    circlePost.setLiked(!circlePost.isLiked());
                    setLikeIcon(circlePost.isLiked());
                    notifyItemChanged(position);
                    // 这里可以添加数据库更新逻辑
                }
            });

            buttonComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 评论的逻辑
                }
            });
        }
        public void setLikeIcon(boolean isLiked) {
            int iconResId = isLiked ? R.drawable.baseline_thumb_up_alt_24 : R.drawable.baseline_thumb_up_off_alt_24;
            buttonLike.setImageResource(iconResId);
        }


        // 隐藏中间四位数字的方法
        private String hideMiddleFourDigits(String number) {
            if (number == null || number.length() < 8) {
                // 如果手机号长度不足8位，直接返回原手机号或提示信息
                return "Invalid number";
            }
            // 取手机号的前三位和后四位，中间用星号替换
            return number.substring(0, 3) + "****" + number.substring(number.length() - 4);
        }

        // bind方法用于将帖子数据绑定到ViewHolder的视图上
        public void bind(CirclePost circlePost) {
            textViewContent.setText(circlePost.getContent());
            if (circlePost.hasImage()) {
                imagePostContent.setVisibility(View.VISIBLE);
                Glide.with(context)
                        .load(circlePost.getImageUrl())
                        .override(300,300)
                        .into(imagePostContent);
            }
//            else {
//                imagePostContent.setVisibility(View.GONE);
//            }
        }
    }
}